<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>轮胎使用记录查询</title>
  <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.0/themes/smoothness/jquery-ui.css">
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://code.jquery.com/ui/1.13.0/jquery-ui.min.js"></script>
  <style>
    .ui-autocomplete {
      max-height: 200px;
      overflow-y: auto;
      overflow-x: hidden;
      z-index: 1000;
    }
    .ui-autocomplete-loading {
      background: white url('https://code.jquery.com/ui/1.13.0/themes/smoothness/images/ui-anim_basic_16x16.gif') right center no-repeat;
      background-size: 16px 16px;
    }
  </style>
</head>
<body>
<div class="container mt-4">
  <h1>轮胎使用记录查询</h1>

  <div th:if="${error}" class="alert alert-warning">
    <span th:text="${error}"></span>
  </div>

  <form th:action="@{/api/tires/usage}" method="post" class="mb-4">
    <div class="row">
      <div class="col-md-8">
        <div class="mb-3">
          <label for="tireNumber" class="form-label">轮胎号 *</label>
          <input type="text" class="form-control" id="tireNumber" name="tireNumber"
                 placeholder="输入轮胎编号，支持自动补全" required th:value="${param.tireNumber}">
          <div class="form-text">
            输入轮胎编号，支持自动补全功能。输入部分编号后从下拉列表中选择完整的轮胎编号。
          </div>
        </div>
      </div>
    </div>

    <button type="submit" class="btn btn-primary">查询</button>
    <a href="/api/tires" class="btn btn-secondary">返回列表</a>
  </form>

  <div class="debug-info" id="debugInfo">
    调试信息将显示在这里...
  </div>

  <div class="card">
    <div class="card-header">
      <h5>查询说明</h5>
    </div>
    <div class="card-body">
      <p>本查询功能可以查看轮胎的以下信息：</p>
      <ul>
        <li>轮胎当前关联的车牌号</li>
        <li>轮胎总使用公里数（仅限已报废轮胎）</li>
        <li>轮胎总使用时间（仅限已报废轮胎）</li>
        <li>轮胎安装信息和使用记录</li>
        <li>轮胎维修和调胎记录</li>
      </ul>
    </div>
  </div>
</div>

<script>
  $(document).ready(function() {
    function updateDebugInfo(message) {
      const timestamp = new Date().toLocaleTimeString();
      const debugInfo = document.getElementById('debugInfo');
      debugInfo.innerHTML = `${timestamp}: ${message}`;
      console.log(message);
    }

    updateDebugInfo("页面加载完成，初始化自动补全功能...");

    // 自动补全功能
    $("#tireNumber").autocomplete({
      source: function(request, response) {
        updateDebugInfo(`发送自动补全请求，关键词: "${request.term}"`);

        $.ajax({
          url: "/api/tires/autocomplete/tire-numbers", // 修正后的URL
          dataType: "json",
          data: {
            term: request.term
          },
          beforeSend: function() {
            $("#tireNumber").addClass("ui-autocomplete-loading");
            updateDebugInfo("正在请求数据...");
          },
          success: function(data) {
            updateDebugInfo(`收到响应，数据条数: ${data.length}`);
            console.log("自动补全数据:", data);
            response(data);
          },
          error: function(xhr, status, error) {
            updateDebugInfo(`请求失败: ${status} - ${error}`);
            console.error("自动补全请求失败:", xhr);
            response([]);
          },
          complete: function() {
            $("#tireNumber").removeClass("ui-autocomplete-loading");
          }
        });
      },
      minLength: 1,
      delay: 300,
      select: function(event, ui) {
        updateDebugInfo(`用户选择了: "${ui.item.value}"`);
        $("#tireNumber").val(ui.item.value);
        return false;
      },
      focus: function(event, ui) {
        event.preventDefault();
      }
    });

    // 监听输入框变化
    $("#tireNumber").on('input', function() {
      updateDebugInfo(`输入框内容变化: "${$(this).val()}"`);
    });

    // 表单提交前的验证
    $("form").submit(function() {
      const tireNumber = $("#tireNumber").val().trim();

      if (tireNumber.length === 0) {
        alert("请输入轮胎编号");
        return false;
      }

      updateDebugInfo(`提交表单，轮胎编号: "${tireNumber}"`);
      return true;
    });

    // 输入框获得焦点时自动选择所有文本，方便用户重新输入
    $("#tireNumber").focus(function() {
      $(this).select();
      updateDebugInfo("输入框获得焦点");
    });

    updateDebugInfo("自动补全功能初始化完成");
  });
</script>
</body>
</html>